package com.yjt.admin.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjt.admin.system.dao.RoleMenuMapper;
import com.yjt.admin.system.entity.RoleMenu;
import com.yjt.admin.system.form.RoleMenuForm;
import com.yjt.admin.system.service.RoleMenuService;
import com.yjt.admin.system.vo.MenuVO;
import com.yjt.common.utils.TreeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色菜单表 服务实现类
 * </p>
 *
 * @author zzp
 * @since 2021-10-08
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {

    @Resource
    private RoleMenuMapper roleMenuMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrUpdate(RoleMenuForm roleMenuForm) {

        //通过角色id删除所有
        this.remove(Wrappers.<RoleMenu>lambdaUpdate().eq(RoleMenu::getRoleId, roleMenuForm.getRoleId()));
        //构造数据
        List<RoleMenu> newList = roleMenuForm.getMenuIdList().stream()
                .map(e -> new RoleMenu("", roleMenuForm.getRoleId(), e)).collect(Collectors.toList());

        //保存数据
       this.saveBatch(newList);
    }

    @Override
    public List<MenuVO> getMenuWithRoleId(String roleId) {
        //查询当前角色下的所有菜单
        List<MenuVO> menuVOList = roleMenuMapper.findMenuByRoleId(roleId);
        if (menuVOList == null || menuVOList.isEmpty()) {
            return null;
        }
        //构造树结构并返回
        return TreeUtil.loopRoot(menuVOList);
    }

    @Override
    public Map<String, List<MenuVO>> getListMenu() {



        return null;
    }
}
